﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Diagnostics;
using System.IO;
using System.Configuration;
using System.Collections;
using Microsoft.VisualBasic;
using Exact_Extension.Entity;
namespace Exact_Extension
{
    public class XMLExport
    {
        ExactDataContext DS;
        Common common;
        IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
        DateTime StartDate;
        public XMLExport(ExactDataContext _DS)
        {
            DS = _DS;
            common = new Common(_DS);
            StartDate = Convert.ToDateTime("01/07/" + DateTime.Now.Year.ToString(), culture);

        }
        #region INVOICE IMPORT PROCESSING
        public void StartProcessImportInvoice(string filexml)
        {
            Process Proc = new Process();
            Proc.StartInfo.FileName = @"ASImport.exe";
            Proc.StartInfo.Arguments = "-r" + DS.Connection.DataSource +  " -D" +DS.Connection.Database + " -u -~ I -URL" + filexml + " -Tinvoices -OPT18 -Oauto";
            Proc.StartInfo.UseShellExecute = false;
            Proc.StartInfo.RedirectStandardError = true;
            Proc.StartInfo.RedirectStandardError = true;
            Proc.StartInfo.Verb = "runas";
            Proc.Start();
           
            Proc.WaitForExit();
            Proc.Close();
        }
      
        public string ExportSalesInvoice(List<ISHCMC_V_StudentListWithDebtor> ListStudent, List<ISHCMC_V_Invoice> ListInvDetail,ref bool flag,ref string error,ref ISHCMC_V_Invoice InvoiceError)
        {
            string filename = ConfigurationSettings.AppSettings["ShareFolderXML"] + @"\INV" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml";
            XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
            XElement elementRoot = new XElement("eExact", new XAttribute(XNamespace.Xmlns + "xsi", ns),
                new XAttribute(ns + "noNamespaceSchemaLocation", "eExact-Schema.xsd"));


            doc.Add(elementRoot);
            XElement elementInvoices = new XElement("Invoices", new XAttribute("companycode", DS.Connection.Database));
            try
            {
                foreach (ISHCMC_V_StudentListWithDebtor itemStudent in ListStudent)
                {

                    foreach (ISHCMC_V_Invoice itemInvDetail in ListInvDetail)
                    {
                        if (itemInvDetail.StudentID == itemStudent.StudentID)
                        {

                            try
                            {
                                if (!common.CheckInvoicedValidated(itemInvDetail.ProformaInvoiceNo + "/" + itemInvDetail.Itemcode))
                                {
                                    XElement elementInvoiceType = new XElement("Invoice");
                                    if (itemInvDetail.Itemcode == "TF" || itemInvDetail.Itemcode == "ADF" || itemInvDetail.Itemcode == "APPF")
                                    {
                                        elementInvoiceType = new XElement("Invoice",

                                        new XAttribute("code", "301"), new XAttribute("type", "V"));
                                        elementInvoices.Add(elementInvoiceType);
                                        
                                    }
                                    else if (itemInvDetail.Itemcode == "COE")
                                    {
                                        elementInvoiceType = new XElement("Invoice",

                                      new XAttribute("code", "302"), new XAttribute("type", "V"));
                                        elementInvoices.Add(elementInvoiceType);
                                        itemInvDetail.ProformaInvoiceNo = itemInvDetail.InvoiceNo;
                                    }
                                    else
                                    {
                                        elementInvoiceType = new XElement("Invoice",

                                        new XAttribute("code", "303"), new XAttribute("type", "V"));
                                        elementInvoices.Add(elementInvoiceType);
                                        itemInvDetail.ProformaInvoiceNo = itemInvDetail.InvoiceNo;
                                    }


                                    XElement elementDescription = new XElement("Description",
                                         itemInvDetail.Description);
                                    elementInvoiceType.Add(elementDescription);


                                    XElement elementYourRef = new XElement("YourRef",
                                    itemInvDetail.ProformaInvoiceNo );
                                    elementInvoiceType.Add(elementYourRef);

                                    XElement elementRef1 = new XElement("Reference1",
                                    itemInvDetail.ID.ToString());
                                    elementInvoiceType.Add(elementRef1);

                                    XElement elementInvoiceDate = new XElement("Date",
                                 itemInvDetail.TransDate.Value.ToString("dd/MM/yyyy",culture));
                                    elementInvoiceType.Add(elementInvoiceDate);

                                    XElement elementCurrency = new XElement("Currency", new XAttribute("code", "VND"));
                                    elementInvoiceType.Add(elementCurrency);

                                    XElement elementOrderBy = new XElement("OrderedBy");
                                    elementInvoiceType.Add(elementOrderBy);
                                    XElement elementOrderByCode = new XElement("Debtor",

                                        new XAttribute("code", itemStudent.DebtorCode.Trim())

                                      );
                                    elementOrderBy.Add(elementOrderByCode);

                                    XElement elementDeliverTo = new XElement("DeliverTo");
                                    elementInvoiceType.Add(elementDeliverTo);
                                    XElement elementDeliverToCode = new XElement("Debtor",

                                        new XAttribute("code", itemStudent.DebtorCode.Trim())
                                   );
                                    elementDeliverTo.Add(elementDeliverToCode);

                                    XElement elementInvoiceTo = new XElement("InvoiceTo");
                                    elementInvoiceType.Add(elementInvoiceTo);
                                    if (itemStudent.InvoiceDebtor != null)
                                    {
                                        XElement elementInvoiceToCode = new XElement("Debtor",

                                            new XAttribute("code", itemStudent.InvoiceDebtor.Trim())

                                          );
                                    }
                                    else
                                    {
                                        XElement elementInvoiceToCode = new XElement("Debtor",

                                           new XAttribute("code", itemStudent.DebtorCode.Trim())

                                         );
                                    }
                                    elementInvoiceTo.Add(elementDeliverToCode);

                                    XElement elementWarehouse = new XElement("Warehouse", new XAttribute("code", "1"));
                                    elementInvoiceType.Add(elementWarehouse);

                                    if (itemInvDetail.DueDate.Value >= DateTime.Now.Date)
                                    {
                                        string days = "00" + DateAndTime.DateDiff(DateAndTime.DateInterval.Day, itemInvDetail.TransDate.Value, itemInvDetail.DueDate.Value).ToString();



                                        XElement elementPaymentCondition = new XElement("PaymentCondition", new XAttribute("code", days.Substring(days.Length - 2, 2)));
                                        elementInvoiceType.Add(elementPaymentCondition);
                                    }
                                    else
                                    {

                                        XElement elementPaymentCondition = new XElement("PaymentCondition", new XAttribute("code", "00"));
                                        elementInvoiceType.Add(elementPaymentCondition);
                                    }

                                    XElement elementDeliveryMethod = new XElement("DeliveryMethod", new XAttribute("code", "DEF"));
                                    elementInvoiceType.Add(elementDeliveryMethod);
                                    XElement elementInvoiceLine = new XElement("InvoiceLine");
                                    elementInvoiceType.Add(elementInvoiceLine);

                                    XElement elementItem = new XElement("Item", new XAttribute("code", itemInvDetail.Itemcode));
                                    elementInvoiceLine.Add(elementItem);

                                    string pricelistcode = common.GetPriceListCode(itemInvDetail.Itemcode, itemStudent, itemStudent.SchoolYear.Substring(5, 4), itemInvDetail.TransDate.Value,itemInvDetail.Section);
                                    XElement elementPriceList = new XElement("PriceList", new XAttribute("code", pricelistcode));
                                    elementInvoiceLine.Add(elementPriceList);

                                    XElement elementPLDescription = new XElement("Description", pricelistcode);
                                    elementPriceList.Add(elementPLDescription);

                                    XElement elementPLCurrency = new XElement("Currency", new XAttribute("code", itemInvDetail.Currency));

                                    XElement elementPLCurrencyDes = new XElement("Description", itemInvDetail.Currency);
                                    elementPLCurrency.Add(elementPLCurrencyDes);
                                    elementPriceList.Add(elementPLCurrency);



                                    XElement elementQuantity = new XElement("Quantity", "1");
                                    elementInvoiceLine.Add(elementQuantity);

                                    XElement elementUnit = new XElement("Unit", new XAttribute("unit", "-"));
                                    elementInvoiceLine.Add(elementUnit);

                                    XElement elementPrice = new XElement("Price");
                                    elementInvoiceLine.Add(elementPrice);
                                    XElement elementPriceValue = new XElement("Value", itemInvDetail.Amount);
                                    elementPrice.Add(elementPriceValue);

                                    if (itemInvDetail.Discount.HasValue)
                                    {
                                        if (itemInvDetail.Discount.Value > 0)
                                        {
                                            XElement elementDiscount = new XElement("Discount");
                                            elementInvoiceLine.Add(elementDiscount);
                                            XElement elementDiscountValue = new XElement("Percentage", itemInvDetail.Discount.Value);
                                            elementDiscount.Add(elementDiscountValue);
                                        }
                                    }
                                    else
                                    {
                                        itemInvDetail.Discount = 0;
                                    }

                                    XElement elementAmount = new XElement("Amount");
                                    elementInvoiceLine.Add(elementAmount);
                                    XElement elementAmountValue = new XElement("Value", itemInvDetail.Amount - (itemInvDetail.Amount * (itemInvDetail.Discount / 100)));
                                    elementAmount.Add(elementAmountValue);
                                    XElement elementAmountCurrency = new XElement("Currency", new XAttribute("code", itemInvDetail.Currency));
                                    elementAmount.Add(elementAmountCurrency);

                                    XElement elementDelivery = new XElement("Delivery");
                                    elementInvoiceLine.Add(elementDelivery);
                                 
                                    XElement elementDeliveryDate = new XElement("Date", itemInvDetail.TransDate.Value.ToString("dd/MM/yyyy",culture));
                                    elementDelivery.Add(elementDeliveryDate);
                 

                                    XElement elementCostCenter = new XElement("Costcenter", new XAttribute("code", itemStudent.School));
                                    elementInvoiceLine.Add(elementCostCenter);

                                   
                                }
                            }
                            catch (Exception exIn)
                            {
                                flag = false;
                                error = exIn.Message;
                                InvoiceError = itemInvDetail;
                                return filename;
                            }
                        }

                    }
                }

                elementRoot.Add(elementInvoices);
                doc.Save(filename);
                flag = true;
                return filename;
            }
            catch (Exception ex)
            {
                flag = false;
                error = ex.Message;
                return filename;
            }

        }
        #endregion

        #region FINANCIAL ENTRY PROCESSING
        public string ExportFinancialEntryCashBank(List<FinEntry> ListData)
        {
            string filename = ConfigurationSettings.AppSettings["ShareFolderXML"] + @"\FINENTRY" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml";
            XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
            XElement elementRoot = new XElement("eExact", new XAttribute(XNamespace.Xmlns + "xsi", ns),
                new XAttribute(ns + "noNamespaceSchemaLocation", "eExact-Schema.xsd"));


            doc.Add(elementRoot);
            XElement elementGLEntries = new XElement("GLEntries");

            foreach (FinEntry item in ListData)
            {
                var queryST = from ST in DS.ISHCMC_V_StudentListWithDebtors
                              where ST.StudentID == item.StudentID
                              select ST;
                 var queryHumres = from Humres in DS.humres
                                      where Humres.usr_id == Environment.UserName
                                      select Humres;
                if (queryST.Count() > 0 && queryHumres.Count() >0)
                {
                    ISHCMC_V_StudentListWithDebtor student = queryST.First();
                    string resourcecode = queryHumres.First().res_id.ToString();
                   
                 
                    XElement elementGLEntry = new XElement("GLEntry");

                    XElement elementGLEntryDesc = new XElement("Description", "Student " + item.StudentID +" Invoice No " + item.InvoiceNo);
                    elementGLEntry.Add(elementGLEntryDesc);

                    XElement elementGLEntryDate = new XElement("Date", item.ReceiptDate.ToString("dd/MM/yyyy"));
                    elementGLEntry.Add(elementGLEntryDate);

                    XElement elementGLEntryJnr = new XElement("Journal", new XAttribute("code", item.JournalNumber.ToString()));
                    XElement elementGLEntryGLAccount = new XElement("GLAccount", new XAttribute("code", item.GLAccount));
                    XElement elementGLEntryGLPaymentInTransit = new XElement("GLPaymentInTransit", new XAttribute("code", item.GLAccountOffset));
                    elementGLEntryJnr.Add(elementGLEntryGLAccount);
                    elementGLEntryJnr.Add(elementGLEntryGLPaymentInTransit);
                    elementGLEntry.Add(elementGLEntryJnr);

                    XElement elementGLEntryCC = new XElement("Costcenter", new XAttribute("code", student.School));
                    elementGLEntry.Add(elementGLEntryCC);

                    XElement elementGLEntryResource = new XElement("Resource", new XAttribute("code", student.School));
                    elementGLEntry.Add(elementGLEntryResource);

                    XElement elementGLEntryAmount = new XElement("Amount");
                    XElement elementGLEntryCurrency = new XElement("Currency", new XAttribute("code", item.Currency));
                        elementGLEntryAmount.Add(elementGLEntryCurrency);
                    elementGLEntry.Add(elementGLEntryAmount);

                        elementGLEntry.Add(this.GetElementFINLineCashBank(item, student, resourcecode, "Credit", item.GLAccountOffset));
                  

                    elementGLEntries.Add(elementGLEntry);
                 
               

                }
            }


            elementRoot.Add(elementGLEntries);
            doc.Save(filename);
            return filename;
        }
        private XElement GetElementFINLineCashBank(FinEntry item, ISHCMC_V_StudentListWithDebtor student, string resourcecode, string type,string glaccount)
        {
            XElement elementGLEntryLine = new XElement("FinEntryLine"
                      , new XAttribute("number", "1")
                      , new XAttribute("type", "N")
                      , new XAttribute("subtype", "Z"));


            XElement elementGLEntryLDate = new XElement("Date", item.ReceiptDate.ToString("dd/MM/yyyy"));
            elementGLEntryLine.Add(elementGLEntryLDate);
            XElement elementGLEntryLGLAccount = new XElement("GLAccount", new XAttribute("code", glaccount));
            elementGLEntryLine.Add(elementGLEntryLGLAccount);

            XElement elementGLEntryLDesc = new XElement("Description", "Student " + item.StudentID + " Invoice No " + item.InvoiceNo);
            elementGLEntryLine.Add(elementGLEntryLDesc);

            XElement elementGLEntryLCC = new XElement("Costcenter", new XAttribute("code", student.School));
            elementGLEntryLine.Add(elementGLEntryLCC);

            XElement elementGLEntryLCU = new XElement("Costunit", new XAttribute("code", student.Grade));
            elementGLEntryLine.Add(elementGLEntryLCU);
            if (item.DebtorCode != null)
            {
                if (item.DebtorCode.Length > 3)
                {
                  
                        XElement elementGLEntryLAccount = new XElement("Debtor", new XAttribute("code", item.DebtorCode.Trim()),
                            new XAttribute("number", item.DebtorCode.Trim()));
                        elementGLEntryLine.Add(elementGLEntryLAccount);
                    
                }
            }
            else
            {
               
                    XElement elementGLEntryLAccount = new XElement("Debtor", new XAttribute("code", student.debnr),
                        new XAttribute("number", student.debnr));
                    elementGLEntryLine.Add(elementGLEntryLAccount);
             
            }
            XElement elementGLEntryLResource = new XElement("Resource", new XAttribute("code", resourcecode));
            elementGLEntryLine.Add(elementGLEntryLResource);

            XElement elementGLEntryLQuantity = new XElement("Quantity", "1");
            elementGLEntryLine.Add(elementGLEntryLQuantity);


            XElement elementGLEntryLAmount = new XElement("Amount");
            if (type == "Debit")
            {
                XElement elementGLEntryLAmountDebit = new XElement("Debit", item.Amount);
                elementGLEntryLAmount.Add(elementGLEntryLAmountDebit);

                XElement elementGLEntryLAmountCredit = new XElement("Credit", "0");
                elementGLEntryLAmount.Add(elementGLEntryLAmountCredit);
            }
            else
            {
                XElement elementGLEntryLAmountDebit = new XElement("Debit","0");
                elementGLEntryLAmount.Add(elementGLEntryLAmountDebit);

                XElement elementGLEntryLAmountCredit = new XElement("Credit",item.Amount);
                elementGLEntryLAmount.Add(elementGLEntryLAmountCredit);
            }

            elementGLEntryLine.Add(elementGLEntryLAmount);
            XElement elementGLEntryFinReference = new XElement("FinReferences");

            XElement elementGLEntryYourRef = new XElement("YourRef",item.Ref);
            elementGLEntryFinReference.Add(elementGLEntryYourRef);
            elementGLEntryLine.Add(elementGLEntryFinReference);

          
            return elementGLEntryLine;
        }



        public string ExportFinancialEntryCashBank_OldSystem(List<FinEntry> ListData)
        {
            string filename = ConfigurationSettings.AppSettings["ShareFolderXML"] + @"\FINENTRY" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml";
            XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
            XElement elementRoot = new XElement("eExact", new XAttribute(XNamespace.Xmlns + "xsi", ns),
                new XAttribute(ns + "noNamespaceSchemaLocation", "eExact-Schema.xsd"));


            doc.Add(elementRoot);
            XElement elementGLEntries = new XElement("GLEntries");

            foreach (FinEntry item in ListData)
            {
               
                var queryHumres = from Humres in DS.humres
                                  where Humres.usr_id == Environment.UserName
                                  select Humres;
                if ( queryHumres.Count() > 0)
                {
                   
                    string resourcecode = queryHumres.First().res_id.ToString();


                    XElement elementGLEntry = new XElement("GLEntry");

                    XElement elementGLEntryDesc = new XElement("Description", "Student " + item.StudentID + " Invoice No " + item.InvoiceNo);
                    elementGLEntry.Add(elementGLEntryDesc);

                    XElement elementGLEntryDate = new XElement("Date", item.ReceiptDate.ToString("dd/MM/yyyy"));
                    elementGLEntry.Add(elementGLEntryDate);

                    XElement elementGLEntryJnr = new XElement("Journal", new XAttribute("code", item.JournalNumber.ToString()));
                    XElement elementGLEntryGLAccount = new XElement("GLAccount", new XAttribute("code", item.GLAccount));
                    XElement elementGLEntryGLPaymentInTransit = new XElement("GLPaymentInTransit", new XAttribute("code", item.GLAccountOffset));
                    elementGLEntryJnr.Add(elementGLEntryGLAccount);
                    elementGLEntryJnr.Add(elementGLEntryGLPaymentInTransit);
                    elementGLEntry.Add(elementGLEntryJnr);

                //    XElement elementGLEntryCC = new XElement("Costcenter", new XAttribute("code", student.School));
                //    elementGLEntry.Add(elementGLEntryCC);

                    XElement elementGLEntryResource = new XElement("Resource", new XAttribute("code", resourcecode));
                    elementGLEntry.Add(elementGLEntryResource);

                    XElement elementGLEntryAmount = new XElement("Amount");
                    XElement elementGLEntryCurrency = new XElement("Currency", new XAttribute("code", item.Currency));
                    elementGLEntryAmount.Add(elementGLEntryCurrency);
                    elementGLEntry.Add(elementGLEntryAmount);

                    elementGLEntry.Add(this.GetElementFINLineCashBank_OldSystem(item,  resourcecode, "Credit", item.GLAccountOffset));


                    elementGLEntries.Add(elementGLEntry);



                }
            }


            elementRoot.Add(elementGLEntries);
            doc.Save(filename);
            return filename;
        }
        private XElement GetElementFINLineCashBank_OldSystem(FinEntry item, string resourcecode, string type, string glaccount)
        {
            XElement elementGLEntryLine = new XElement("FinEntryLine"
                      , new XAttribute("number", "1")
                      , new XAttribute("type", "N")
                      , new XAttribute("subtype", "Z"));


            XElement elementGLEntryLDate = new XElement("Date", item.ReceiptDate.ToString("dd/MM/yyyy"));
            elementGLEntryLine.Add(elementGLEntryLDate);
            XElement elementGLEntryLGLAccount = new XElement("GLAccount", new XAttribute("code", glaccount));
            elementGLEntryLine.Add(elementGLEntryLGLAccount);

            XElement elementGLEntryLDesc = new XElement("Description", "Student " + item.StudentID + " Invoice No " + item.InvoiceNo);
            elementGLEntryLine.Add(elementGLEntryLDesc);

         //   XElement elementGLEntryLCC = new XElement("Costcenter", new XAttribute("code", student.School));
         //   elementGLEntryLine.Add(elementGLEntryLCC);

         //   XElement elementGLEntryLCU = new XElement("Costunit", new XAttribute("code", student.Grade));
        //    elementGLEntryLine.Add(elementGLEntryLCU);
            if (item.DebtorCode != null)
            {
                if (item.DebtorCode.Length > 3)
                {

                    XElement elementGLEntryLAccount = new XElement("Debtor", new XAttribute("code", item.DebtorCode.Trim()),
                        new XAttribute("number", item.DebtorCode.Trim()));
                    elementGLEntryLine.Add(elementGLEntryLAccount);

                }
            }
          
            XElement elementGLEntryLResource = new XElement("Resource", new XAttribute("code", resourcecode));
            elementGLEntryLine.Add(elementGLEntryLResource);

            XElement elementGLEntryLQuantity = new XElement("Quantity", "1");
            elementGLEntryLine.Add(elementGLEntryLQuantity);


            XElement elementGLEntryLAmount = new XElement("Amount");
            if (type == "Debit")
            {
                XElement elementGLEntryLAmountDebit = new XElement("Debit", item.Amount);
                elementGLEntryLAmount.Add(elementGLEntryLAmountDebit);

                XElement elementGLEntryLAmountCredit = new XElement("Credit", "0");
                elementGLEntryLAmount.Add(elementGLEntryLAmountCredit);
            }
            else
            {
                XElement elementGLEntryLAmountDebit = new XElement("Debit", "0");
                elementGLEntryLAmount.Add(elementGLEntryLAmountDebit);

                XElement elementGLEntryLAmountCredit = new XElement("Credit", item.Amount);
                elementGLEntryLAmount.Add(elementGLEntryLAmountCredit);
            }

            elementGLEntryLine.Add(elementGLEntryLAmount);
            XElement elementGLEntryFinReference = new XElement("FinReferences");

            XElement elementGLEntryYourRef = new XElement("YourRef", item.InvoiceNo);
            elementGLEntryFinReference.Add(elementGLEntryYourRef);
            elementGLEntryLine.Add(elementGLEntryFinReference);


            return elementGLEntryLine;
        }


        public string ExportFinancialEntryRevenue_OldSystem(List<FinEntry> ListData)
        {
            string filename = ConfigurationSettings.AppSettings["ShareFolderXML"] + @"\FINENTRYREV" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml";
            XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
            XElement elementRoot = new XElement("eExact", new XAttribute(XNamespace.Xmlns + "xsi", ns),
                new XAttribute(ns + "noNamespaceSchemaLocation", "eExact-Schema.xsd"));


            doc.Add(elementRoot);
            XElement elementGLEntries = new XElement("GLEntries");
            int i = 1;
            foreach (FinEntry item in ListData)
            {

                var queryHumres = from Humres in DS.humres
                                  where Humres.usr_id == Environment.UserName
                                  select Humres;
                if (queryHumres.Count() > 0)
                {

                    string resourcecode = queryHumres.First().res_id.ToString();


                    XElement elementGLEntry = new XElement("GLEntry");

                    XElement elementGLEntryDesc = new XElement("Description", item.Description);
                    elementGLEntry.Add(elementGLEntryDesc);

                    XElement elementGLEntryDate = new XElement("Date", item.ReceiptDate.ToString("dd/MM/yyyy"));
                    elementGLEntry.Add(elementGLEntryDate);

                    XElement elementGLEntryJnr = new XElement("Journal", new XAttribute("code", item.JournalNumber.ToString()));
                
     
                    
                    elementGLEntry.Add(elementGLEntryJnr);

                    //    XElement elementGLEntryCC = new XElement("Costcenter", new XAttribute("code", student.School));
                    //    elementGLEntry.Add(elementGLEntryCC);

                    XElement elementGLEntryResource = new XElement("Resource", new XAttribute("code", resourcecode));
                    elementGLEntry.Add(elementGLEntryResource);

                    XElement elementGLEntryAmount = new XElement("Amount");
                    XElement elementGLEntryCurrency = new XElement("Currency", new XAttribute("code", item.Currency));
                    elementGLEntryAmount.Add(elementGLEntryCurrency);
                    elementGLEntry.Add(elementGLEntryAmount);

                    elementGLEntry.Add(this.GetElementFINLineRevenue_OldSystem(item, resourcecode, "Debit", item.GLAccount,i));
                    elementGLEntry.Add(this.GetElementFINLineRevenue_OldSystem(item, resourcecode, "Credit", item.GLAccountOffset,i));

                    elementGLEntries.Add(elementGLEntry);

                    i++;

                }
            }


            elementRoot.Add(elementGLEntries);
            doc.Save(filename);
            return filename;
        }
        private XElement GetElementFINLineRevenue_OldSystem(FinEntry item, string resourcecode, string type, string glaccount,int i)
        {
            XElement elementGLEntryLine = new XElement("FinEntryLine"
                      , new XAttribute("number", i.ToString())
                      , new XAttribute("type", "N")
                      , new XAttribute("subtype", "N"));


            XElement elementGLEntryLDate = new XElement("Date", item.ReceiptDate.ToString("dd/MM/yyyy"));
            elementGLEntryLine.Add(elementGLEntryLDate);
            XElement elementGLEntryLGLAccount = new XElement("GLAccount", new XAttribute("code", glaccount));
            elementGLEntryLine.Add(elementGLEntryLGLAccount);

            XElement elementGLEntryLDesc = new XElement("Description",item.Description);
            elementGLEntryLine.Add(elementGLEntryLDesc);

            //   XElement elementGLEntryLCC = new XElement("Costcenter", new XAttribute("code", student.School));
            //   elementGLEntryLine.Add(elementGLEntryLCC);

            //   XElement elementGLEntryLCU = new XElement("Costunit", new XAttribute("code", student.Grade));
            //    elementGLEntryLine.Add(elementGLEntryLCU);
  

                    XElement elementGLEntryLAccount = new XElement("Debtor", new XAttribute("code", "000000"),
                        new XAttribute("number", "000000"));
                    elementGLEntryLine.Add(elementGLEntryLAccount);


            XElement elementGLEntryLResource = new XElement("Resource", new XAttribute("code", resourcecode));
            elementGLEntryLine.Add(elementGLEntryLResource);

            XElement elementGLEntryLQuantity = new XElement("Quantity", "1");
            elementGLEntryLine.Add(elementGLEntryLQuantity);


            XElement elementGLEntryLAmount = new XElement("Amount");
            if (type == "Debit")
            {
                XElement elementGLEntryLAmountDebit = new XElement("Debit", item.Amount);
                elementGLEntryLAmount.Add(elementGLEntryLAmountDebit);

                XElement elementGLEntryLAmountCredit = new XElement("Credit", "0");
                elementGLEntryLAmount.Add(elementGLEntryLAmountCredit);
            }
            else
            {
                XElement elementGLEntryLAmountDebit = new XElement("Debit", "0");
                elementGLEntryLAmount.Add(elementGLEntryLAmountDebit);

                XElement elementGLEntryLAmountCredit = new XElement("Credit", item.Amount);
                elementGLEntryLAmount.Add(elementGLEntryLAmountCredit);
            }

            elementGLEntryLine.Add(elementGLEntryLAmount);
            XElement elementGLEntryFinReference = new XElement("FinReferences");

            XElement elementGLEntryYourRef = new XElement("YourRef", item.Description);
            elementGLEntryFinReference.Add(elementGLEntryYourRef);
            elementGLEntryLine.Add(elementGLEntryFinReference);


            return elementGLEntryLine;
        }

        public void StartProcessImportFIN(string filexml)
        {
            Process Proc = new Process();
            Proc.StartInfo.FileName = @"ASImport.exe";
            Proc.StartInfo.Arguments = "-r" + DS.Connection.DataSource + " -D" + DS.Connection.Database + " -u -~ I -URL" + filexml + " -TGLENTRIES -OPT18 -Oauto";
            Proc.StartInfo.UseShellExecute = false;
            Proc.StartInfo.RedirectStandardError = true;
            Proc.StartInfo.RedirectStandardError = true;
            Proc.StartInfo.Verb = "runas";
            Proc.Start();

            Proc.WaitForExit();
            Proc.Close();
        }
        #endregion

        #region Debtor & Student
        public string ExportXMLInvoiceDebtor(ISHCMC_DebtorRegister itemDebtor)
        {
            string filename = ConfigurationSettings.AppSettings["ShareFolderXML"] + @"\INVDEBTOR" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml";
            XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
            XElement elementRoot = new XElement("eExact", new XAttribute(XNamespace.Xmlns + "xsi", ns),
                new XAttribute(ns + "noNamespaceSchemaLocation", "eExact-Schema.xsd"));


            doc.Add(elementRoot);
            XElement elementAccounts = new XElement("Accounts");
            elementRoot.Add(elementAccounts);


            




                string DebtorID = itemDebtor.InvoiceDebtor;
                
                string DebtorName = itemDebtor.BillingName;
                string Address1 = itemDebtor.BillingAddress1;
                string Address2 = itemDebtor.BillingAddress2;
                string Address3 = itemDebtor.BillingAddress3;
                if (itemDebtor.TaxInvoiceAddress1 != null || itemDebtor.TaxInvoiceAddress1.Length > 1)
                {
                    Address1 = itemDebtor.TaxInvoiceAddress1;
                }
                if (itemDebtor.TaxInvoiceAddress2 != null || itemDebtor.TaxInvoiceAddress2.Length > 1)
                {
                    Address2 = itemDebtor.TaxInvoiceAddress2;
                }
                if (itemDebtor.TaxInvoiceAddress3 != null || itemDebtor.TaxInvoiceAddress3.Length > 1)
                {
                    Address3 = itemDebtor.TaxInvoiceAddress3;
                }
                string DebtorCode = itemDebtor.InvoiceDebtor;
                string AccountCode = itemDebtor.InvoiceDebtor;
                string Phone = itemDebtor.Contactphone;
                string Fax = "";
                string Email = itemDebtor.Contactemail;
                string HomePage = "";

                while (DebtorCode.Length < 6)
                {
                    DebtorCode = " " + DebtorCode;
                }

                while (AccountCode.Length < 20)
                {
                    AccountCode = " " + AccountCode;
                }



                XElement elementAccount = new XElement("Account",
                                 new XAttribute("code", AccountCode),
                                 new XAttribute("status", "A"),
                                 new XAttribute("type", "C"));

                XElement elementName = new XElement("Name", DebtorName);
                elementAccount.Add(elementName);
                XElement elementPhone = new XElement("Phone", Phone);
                elementAccount.Add(elementPhone);
                XElement elementFax = new XElement("Fax", Fax);
                elementAccount.Add(elementFax);
                XElement elementEmail = new XElement("Email", Email);
                elementAccount.Add(elementEmail);
                XElement elementHomePage = new XElement("HomePage", HomePage);
                elementAccount.Add(elementHomePage);

                XElement elementContacts = new XElement("Contacts");
                elementAccount.Add(elementContacts);

                XElement elementContact = new XElement("Contact",
                    new XAttribute("default", "1"),
                    new XAttribute("gender", "O"),
                    new XAttribute("status", "A"));


                XElement elementLastName = new XElement("LastName", itemDebtor.ContactName1);
                elementContact.Add(elementLastName);
                XElement elementFirstName = new XElement("FirstName", "");
                elementContact.Add(elementFirstName);
                XElement elementTitle = new XElement("Title",
                    new XAttribute("code", "LS"));
                elementContact.Add(elementTitle);

                XElement elementAddresses = new XElement("Addresses");
                elementContact.Add(elementAddresses);

                string[] AddressType = { "D", "I", "P", "V" };
                foreach (string itemAddressType in AddressType)
                {
                    XElement elementAddress = new XElement("Address",
                        new XAttribute("type", itemAddressType),
                        new XAttribute("desc", ""));


                    XElement elementAddressLine1 = new XElement("AddressLine1", Address1);
                    elementAddress.Add(elementAddressLine1);
                    XElement elementAddressLine2 = new XElement("AddressLine2", Address2);
                    elementAddress.Add(elementAddressLine2);
                    XElement elementAddressLine3 = new XElement("AddressLine2", Address3);
                    elementAddress.Add(elementAddressLine3);
                    XElement elementPostalCode = new XElement("PostalCode", "");
                    elementAddress.Add(elementPostalCode);
                    XElement elementCity = new XElement("City", "");
                    elementAddress.Add(elementCity);
                    XElement elementState = new XElement("State", new XAttribute("code", ""));
                    elementAddress.Add(elementState);

                    XElement elementCountry = new XElement("Country", new XAttribute("code", "VN"));
                    elementAddress.Add(elementCountry);
                    XElement elementPhoneContact = new XElement("Phone");
                    elementAddress.Add(elementPhoneContact);

                    XElement elementFaxContact = new XElement("Fax");
                    elementAddress.Add(elementPhoneContact);

                    elementAddresses.Add(elementAddress);
                }
                XElement elementLanguageCode = new XElement("Language", new XAttribute("code", "EN"));
                elementContact.Add(elementLanguageCode);
                elementContacts.Add(elementContact);

                XElement elementManager = new XElement("Manager", new XAttribute("number", "1"));
                elementAccount.Add(elementManager);

                XElement elementDebtor = new XElement("Debtor",
                    new XAttribute("number", DebtorCode),
                    new XAttribute("code", AccountCode));
                elementAccount.Add(elementDebtor);

                XElement elementCurrency = new XElement("Currency",
                    new XAttribute("code", "VND"));
                elementDebtor.Add(elementCurrency);

                XElement elementSecurity = new XElement("SecurityLevel", "10");
                elementDebtor.Add(elementSecurity);

                XElement elementVAT = new XElement("VATLiability", "L");
                elementAccount.Add(elementVAT);
                XElement elementVATNumber = new XElement("VATNumber", itemDebtor.VATCode);
                elementAccount.Add(elementVATNumber);

                XElement elementCompanySize = new XElement("CompanySize", new XAttribute("code", "UNKNOWN"));
                elementAccount.Add(elementCompanySize);

                XElement elementCompanyOrigin = new XElement("CompanyOrgin", new XAttribute("code", "P"));
                elementAccount.Add(elementCompanyOrigin);

                XElement elementCompanyRating = new XElement("CompanyRating", new XAttribute("code", "1"));
                elementAccount.Add(elementCompanyOrigin);


                if (itemDebtor.PayerType == "FA")
                {
                    XElement elementAccountCategory = new XElement("AccountCategory", new XAttribute("code", "FA"));
                    elementAccount.Add(elementAccountCategory);
                }
                else
                {

                    XElement elementAccountCategory = new XElement("AccountCategory", new XAttribute("code", "CO"));
                    elementAccount.Add(elementAccountCategory);
                }

                if (itemDebtor.TaxInvoiceDisplayName != null || itemDebtor.TaxInvoiceDisplayName.Length > 2)
                {
                    XElement elementPayeeName = new XElement("PayeeName", itemDebtor.TaxInvoiceDisplayName);
                    elementAccount.Add(elementPayeeName);
                }

                elementAccounts.Add(elementAccount);



         

            doc.Save(filename);
            return filename;

        }     
        public string ExportXMLStudent(ISHCMC_DebtorRegister itemDebtor)
        {
            string filename = ConfigurationSettings.AppSettings["ShareFolderXML"] + @"\Student" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml";
            XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
            XElement elementRoot = new XElement("eExact", new XAttribute(XNamespace.Xmlns + "xsi", ns),
                new XAttribute(ns + "noNamespaceSchemaLocation", "eExact-Schema.xsd"));


            doc.Add(elementRoot);
            XElement elementAccounts = new XElement("Accounts");
            elementRoot.Add(elementAccounts);





                string DebtorID = itemDebtor.StudentIDExact;
                string DebtorName = itemDebtor.StudentLastName.ToUpper() + " " + itemDebtor.StudentFirstName.ToUpper();
                string Address1 = itemDebtor.Contactaddress1;
                string Address2 = itemDebtor.Contactaddress2;
                string Address3 = itemDebtor.Contactaddress3;
              
                string DebtorCode = DebtorID.ToString();
                string AccountCode = DebtorID.ToString();
                string Phone = itemDebtor.Homephone;
                string Fax = "";
                string Email = itemDebtor.Contactemail;
                string HomePage = "";

                while (DebtorCode.Length < 6)
                {
                    DebtorCode = " " + DebtorCode;
                }

                while (AccountCode.Length < 20)
                {
                    AccountCode = " " + AccountCode;
                }



                XElement elementAccount = new XElement("Account",
                                 new XAttribute("code", AccountCode),
                                 new XAttribute("status", "A"),
                                 new XAttribute("type", "C"));

                XElement elementName = new XElement("Name", DebtorName);
                elementAccount.Add(elementName);
                XElement elementPhone = new XElement("Phone", Phone);
                elementAccount.Add(elementPhone);
                XElement elementFax = new XElement("Fax", Fax);
                elementAccount.Add(elementFax);
                XElement elementEmail = new XElement("Email", Email);
                elementAccount.Add(elementEmail);
                XElement elementHomePage = new XElement("HomePage", HomePage);
                elementAccount.Add(elementHomePage);

                XElement elementContacts = new XElement("Contacts");
                elementAccount.Add(elementContacts);

                #region Contact Father
                XElement elementContactFAR = new XElement("Contact",
                    new XAttribute("default", "1"),
                    new XAttribute("gender", "O"),
                    new XAttribute("status", "A"));

                if (itemDebtor.FatherName != null || itemDebtor.FatherName.Length > 0)
                {
                    XElement elementLastNameFAR = new XElement("LastName", itemDebtor.FatherName);
                    elementContactFAR.Add(elementLastNameFAR);
                    XElement elementFirstNameFAR = new XElement("FirstName", "");
                    elementContactFAR.Add(elementFirstNameFAR);
                    XElement elementTitleFAR = new XElement("Title",
                        new XAttribute("code", "FAR"));
                    elementContactFAR.Add(elementTitleFAR);

                    XElement elementAddressesFAR = new XElement("Addresses");
                    elementContactFAR.Add(elementAddressesFAR);

                    string[] AddressTypeFAR = { "D", "I", "P", "V" };
                    foreach (string itemAddressTypeFAR in AddressTypeFAR)
                    {
                        XElement elementAddressFAR = new XElement("Address",
                            new XAttribute("type", itemAddressTypeFAR),
                            new XAttribute("desc", ""));


                        XElement elementAddressLineFAR1 = new XElement("AddressLine1", itemDebtor.Contactaddress1);
                        elementAddressFAR.Add(elementAddressLineFAR1);
                        XElement elementAddressLineFAR2 = new XElement("AddressLine2", itemDebtor.Contactaddress2);
                        elementAddressFAR.Add(elementAddressLineFAR2);
                        XElement elementAddressLineFAR3 = new XElement("AddressLine3", itemDebtor.Contactaddress3);
                        elementAddressFAR.Add(elementAddressLineFAR3);
                        XElement elementPostalCodeFAR = new XElement("PostalCode", "");
                        elementAddressFAR.Add(elementPostalCodeFAR);
                        XElement elementCityFAR = new XElement("City", "");
                        elementAddressFAR.Add(elementCityFAR);
                        XElement elementStateFAR = new XElement("State", new XAttribute("code", ""));
                        elementAddressFAR.Add(elementStateFAR);

                        XElement elementCountryFAR = new XElement("Country", new XAttribute("code", "VN"));
                        elementAddressFAR.Add(elementCountryFAR);
                        XElement elementPhoneContactFAR = new XElement("Phone", itemDebtor.FatherCellPhone);
                        elementAddressFAR.Add(elementPhoneContactFAR);

                        XElement elementFaxContactFAR = new XElement("Fax");
                        elementAddressFAR.Add(elementPhoneContactFAR);

                        elementAddressesFAR.Add(elementAddressFAR);

                    }
                    XElement elementLanguageCodeFAR = new XElement("Language", new XAttribute("code", "EN"));
                    elementContactFAR.Add(elementLanguageCodeFAR);
                    XElement elementContactEmailFAR = new XElement("Email", itemDebtor.FatherEmail);
                    elementContactFAR.Add(elementContactEmailFAR);
                    elementContacts.Add(elementContactFAR);
                }
                #endregion
       

                #region Contact Mother
                if (itemDebtor.MotherName != null || itemDebtor.MotherName.Length > 0)
                {
                    XElement elementContactMOT = new XElement("Contact",
                  new XAttribute("default", "1"),
                  new XAttribute("gender", "O"),
                  new XAttribute("status", "A"));


                    XElement elementLastNameMOT = new XElement("LastName", itemDebtor.MotherName);
                    elementContactMOT.Add(elementLastNameMOT);
                    XElement elementFirstNameMOT = new XElement("FirstName", "");
                    elementContactMOT.Add(elementFirstNameMOT);
                    XElement elementTitleMOT = new XElement("Title",
                        new XAttribute("code", "MOT"));
                    elementContactMOT.Add(elementTitleMOT);

                    XElement elementAddressesMOT = new XElement("Addresses");
                    elementContactMOT.Add(elementAddressesMOT);

                    string[] AddressTypeMOT = { "D", "I", "P", "V" };
                    foreach (string itemAddressTypeMOT in AddressTypeMOT)
                    {
                        XElement elementAddressMOT = new XElement("Address",
                            new XAttribute("type", itemAddressTypeMOT),
                            new XAttribute("desc", ""));


                        XElement elementAddressLineMOT1 = new XElement("AddressLine1", itemDebtor.Contactaddress1);
                        elementAddressMOT.Add(elementAddressLineMOT1);
                        XElement elementAddressLineMOT2 = new XElement("AddressLine2", itemDebtor.Contactaddress2);
                        elementAddressMOT.Add(elementAddressLineMOT2);
                        XElement elementAddressLineMOT3 = new XElement("AddressLine3", itemDebtor.Contactaddress3);
                        elementAddressMOT.Add(elementAddressLineMOT3);
                        XElement elementPostalCodeMOT = new XElement("PostalCode", "");
                        elementAddressMOT.Add(elementPostalCodeMOT);
                        XElement elementCityMOT = new XElement("City", "");
                        elementAddressMOT.Add(elementCityMOT);
                        XElement elementStateMOT = new XElement("State", new XAttribute("code", ""));
                        elementAddressMOT.Add(elementStateMOT);

                        XElement elementCountryMOT = new XElement("Country", new XAttribute("code", "VN"));
                        elementAddressMOT.Add(elementCountryMOT);
                        XElement elementPhoneContactMOT = new XElement("Phone", itemDebtor.MotherCellPhone);
                        elementAddressMOT.Add(elementPhoneContactMOT);

                        XElement elementFaxContactMOT = new XElement("Fax");
                        elementAddressMOT.Add(elementPhoneContactMOT);

                        elementAddressesMOT.Add(elementAddressMOT);

                    }
                    XElement elementLanguageCodeMOT = new XElement("Language", new XAttribute("code", "EN"));
                    elementContactMOT.Add(elementLanguageCodeMOT);
                    XElement elementContactEmailMOT = new XElement("Email", itemDebtor.MotherEmail);
                    elementContactMOT.Add(elementContactEmailMOT);
                    elementContacts.Add(elementContactMOT);
                }
                #endregion

                #region OTHER CONTACT 1
                if ((itemDebtor.ContactName1 != null && itemDebtor.ContactName1.Trim().Length > 1) || (itemDebtor.ContactName2 != null && itemDebtor.ContactName2.Trim().Length > 1))
                {
                    XElement elementContactOTH = new XElement("Contact",
                      new XAttribute("default", "1"),
                      new XAttribute("gender", "O"),
                      new XAttribute("status", "A"));


                    XElement elementLastNameOTH = new XElement("LastName", itemDebtor.ContactName1);
                    elementContactOTH.Add(elementLastNameOTH);
                    XElement elementFirstNameOTH = new XElement("FirstName", itemDebtor.ContactName2);
                    elementContactOTH.Add(elementFirstNameOTH);
                    XElement elementTitleOTH = new XElement("Title",
                        new XAttribute("code", "OT"));
                    elementContactOTH.Add(elementTitleOTH);

                    XElement elementAddressesOTH = new XElement("Addresses");
                    elementContactOTH.Add(elementAddressesOTH);

                    string[] AddressTypeOTH = { "D", "I", "P", "V" };
                    foreach (string itemAddressTypeOTH in AddressTypeOTH)
                    {
                        XElement elementAddressOTH = new XElement("Address",
                            new XAttribute("type", itemAddressTypeOTH),
                            new XAttribute("desc", ""));


                        XElement elementAddressLineOTH1 = new XElement("AddressLine1", itemDebtor.Contactaddress1);
                        elementAddressOTH.Add(elementAddressLineOTH1);
                        XElement elementAddressLineOTH2 = new XElement("AddressLine2", itemDebtor.Contactaddress2);
                        elementAddressOTH.Add(elementAddressLineOTH2);
                        XElement elementAddressLineOTH3 = new XElement("AddressLine3", itemDebtor.Contactaddress3);
                        elementAddressOTH.Add(elementAddressLineOTH3);
                        XElement elementPostalCodeOTH = new XElement("PostalCode", "");
                        elementAddressOTH.Add(elementPostalCodeOTH);
                        XElement elementCityOTH = new XElement("City", "");
                        elementAddressOTH.Add(elementCityOTH);
                        XElement elementStateOTH = new XElement("State", new XAttribute("code", ""));
                        elementAddressOTH.Add(elementStateOTH);

                        XElement elementCountryOTH = new XElement("Country", new XAttribute("code", "VN"));
                        elementAddressOTH.Add(elementCountryOTH);
                        XElement elementPhoneContactOTH = new XElement("Phone", itemDebtor.Contactphone);
                        elementAddressOTH.Add(elementPhoneContactOTH);

                        XElement elementFaxContactOTH = new XElement("Fax");
                        elementAddressOTH.Add(elementPhoneContactOTH);

                        elementAddressesOTH.Add(elementAddressOTH);

                    }
                    XElement elementLanguageCodeOTH = new XElement("Language", new XAttribute("code", "EN"));
                    elementContactOTH.Add(elementLanguageCodeOTH);
                    XElement elementContactEmailOTH = new XElement("Email", itemDebtor.Contactemail);
                    elementContactOTH.Add(elementContactEmailOTH);
                    elementContacts.Add(elementContactOTH);
                }
                #endregion


                XElement elementManager = new XElement("Manager", new XAttribute("number", "1"));
                elementAccount.Add(elementManager);

                XElement elementDebtor = new XElement("Debtor",
                    new XAttribute("number", DebtorCode),
                    new XAttribute("code", AccountCode));
                elementAccount.Add(elementDebtor);

                XElement elementCurrency = new XElement("Currency",
                    new XAttribute("code", "VND"));
                elementDebtor.Add(elementCurrency);

                XElement elementSecurity = new XElement("SecurityLevel", "10");
                elementDebtor.Add(elementSecurity);

                XElement elementInvoiceDebtor = new XElement("DebtorInvoice", new XAttribute("code",itemDebtor.InvoiceDebtor),
                    new XAttribute("number",itemDebtor.InvoiceDebtor));
                elementDebtor.Add(elementInvoiceDebtor);

                XElement elementVAT = new XElement("VATLiability", "L");
                elementAccount.Add(elementVAT);

                XElement elementVATNumber = new XElement("VATNumber", itemDebtor.VATCode);
                elementAccount.Add(elementVATNumber);

                XElement elementCompanySize = new XElement("CompanySize", new XAttribute("code", "UNKNOWN"));
                elementAccount.Add(elementCompanySize);

                XElement elementCompanyOrigin = new XElement("CompanyOrgin", new XAttribute("code", "P"));
                elementAccount.Add(elementCompanyOrigin);

                XElement elementCompanyRating = new XElement("CompanyRating", new XAttribute("code", "1"));
                elementAccount.Add(elementCompanyOrigin);



                XElement elementAccountCategory = new XElement("AccountCategory", new XAttribute("code", "ST"));
                elementAccount.Add(elementAccountCategory);

                if (itemDebtor.TaxInvoiceDisplayName != null || itemDebtor.TaxInvoiceDisplayName.Length > 2)
                {
                    XElement elementPayeeName = new XElement("PayeeName",itemDebtor.TaxInvoiceDisplayName);
                    elementAccount.Add(elementPayeeName);
                }

                XElement elementFreeField = new XElement("FreeFields");
                XElement elementFreeText = new XElement("FreeTexts");
                XElement elementFreeText1 = new XElement("FreeText", new XAttribute("number", "1"), new XAttribute("label", "TextField1"),itemDebtor.School);
                elementFreeText.Add(elementFreeText1);
                XElement elementFreeText2 = new XElement("FreeText", new XAttribute("number", "2"), new XAttribute("label", "TextField2"), itemDebtor.Grade);
                elementFreeText.Add(elementFreeText2);
                XElement elementFreeText3 = new XElement("FreeText", new XAttribute("number", "3"), new XAttribute("label", "TextField3"), itemDebtor.Grade);
                elementFreeText.Add(elementFreeText3);
                XElement elementFreeText4 = new XElement("FreeText", new XAttribute("number", "4"), new XAttribute("label", "TextField4"), itemDebtor.StudentIDIS);
                elementFreeText.Add(elementFreeText4);
                XElement elementFreeText5 = new XElement("FreeText", new XAttribute("number", "5"), new XAttribute("label", "TextField5"), itemDebtor.SchoolYear);
                elementFreeText.Add(elementFreeText5);
                XElement elementFreeText6 = new XElement("FreeText", new XAttribute("number", "6"), new XAttribute("label", "TextField6"), itemDebtor.PaymentPlan);
                elementFreeText.Add(elementFreeText6);
                XElement elementFreeText7 = new XElement("FreeText", new XAttribute("number", "7"), new XAttribute("label", "TextField7"), itemDebtor.BillingAddress1);
                elementFreeText.Add(elementFreeText7);
                XElement elementFreeText8 = new XElement("FreeText", new XAttribute("number", "8"), new XAttribute("label", "TextField8"), itemDebtor.BillingAddress2);
                elementFreeText.Add(elementFreeText8);
                XElement elementFreeText9 = new XElement("FreeText", new XAttribute("number", "9"), new XAttribute("label", "TextField9"), itemDebtor.BillingAddress3);
                elementFreeText.Add(elementFreeText9);
                XElement elementFreeText10 = new XElement("FreeText", new XAttribute("number", "10"), new XAttribute("label", "TextField9"), itemDebtor.FatherEmail);
                elementFreeText.Add(elementFreeText10);
                XElement elementFreeText11 = new XElement("FreeText", new XAttribute("number", "11"), new XAttribute("label", "TextField9"), itemDebtor.MotherEmail);
                elementFreeText.Add(elementFreeText11);
                XElement elementFreeText13 = new XElement("FreeText", new XAttribute("number", "13"), new XAttribute("label", "TextField13"), itemDebtor.Attention);
                elementFreeText.Add(elementFreeText13);
                XElement elementFreeText14 = new XElement("FreeText", new XAttribute("number", "14"), new XAttribute("label", "TextField14"), itemDebtor.Gender);
                elementFreeText.Add(elementFreeText14);
               
                
                
                elementFreeField.Add(elementFreeText);

                XElement elementFreeDate = new XElement("FreeDates");

                XElement elementFreeDate1 = new XElement("FreeDate", new XAttribute("number", "1"), new XAttribute("label", "DateField1"),itemDebtor.ActualEntryDate.Value.ToString("dd/MM/yyyy",culture));
                elementFreeDate.Add(elementFreeDate1);

                XElement elementFreeDate2 = new XElement("FreeDate", new XAttribute("number", "2"), new XAttribute("label", "DateField2"), itemDebtor.DOB.Value.ToString("dd/MM/yyyy",culture));
                elementFreeDate.Add(elementFreeDate2);
            
                elementFreeField.Add(elementFreeDate);

                XElement elementYesNo = new XElement("FreeYesNos");
                XElement elementNumber = new XElement("FreeNumbers");
                if (itemDebtor.COEAllocated.HasValue)
                {
                    if (Convert.ToBoolean(itemDebtor.COEAllocated.Value) == true)
                    {
                        XElement elementYesNo1 = new XElement("FreeYesNo", new XAttribute("number", "1"), new XAttribute("label", "YesNoField1"), "1");
                        elementYesNo.Add(elementYesNo1);
                        if (itemDebtor.COENumber > 0)
                        {
                            XElement elementNumber1 = new XElement("FreeNumber", new XAttribute("number", "1"), new XAttribute("label", "NumberField1"), itemDebtor.COENumber.Value.ToString());
                            elementNumber.Add(elementNumber1);
                        }
                    }
                }
                if (itemDebtor.COENew.HasValue)
                {
                    if (Convert.ToBoolean(itemDebtor.COENew.Value) == true)
                    {
                        XElement elementYesNo1 = new XElement("FreeYesNo", new XAttribute("number", "1"), new XAttribute("label", "YesNoField1"), "1");
                        elementYesNo.Add(elementYesNo1);
                    }
                }
                if (itemDebtor.Halfday.HasValue)
                {
                    if (Convert.ToBoolean(itemDebtor.Halfday.Value) == true)
                    {
                        XElement elementYesNo2 = new XElement("FreeYesNo", new XAttribute("number", "2"), new XAttribute("label", "YesNoField2"), "1");
                        elementYesNo.Add(elementYesNo2);
                    }
                }
                if (itemDebtor.ADF.HasValue)
                {
                    if (Convert.ToBoolean(itemDebtor.ADF.Value) == true)
                    {
                        XElement elementYesNo3 = new XElement("FreeYesNo", new XAttribute("number", "3"), new XAttribute("label", "YesNoField3"), "1");
                        elementYesNo.Add(elementYesNo3);
                    }
                }
                elementFreeField.Add(elementYesNo);
                elementFreeField.Add(elementNumber);
            
            

                elementAccount.Add(elementFreeField);
                elementAccounts.Add(elementAccount);




            doc.Save(filename);
            return filename;

        }
        public void StartProcessImportDebtor(string filexml)
        {
            Process Proc = new Process();
            Proc.StartInfo.FileName = @"ASImport.exe";
            Proc.StartInfo.Arguments = "-r" + DS.Connection.DataSource + " -D" + DS.Connection.Database + " -u -~ I -URL" + filexml + " -Tdebtors -OPT18 -Oauto";
            Proc.StartInfo.UseShellExecute = false;
            Proc.StartInfo.RedirectStandardError = true;
            Proc.StartInfo.RedirectStandardError = true;
            Proc.StartInfo.Verb = "runas";
            Proc.Start();

            Proc.WaitForExit();
            Proc.Close();
        }
        #endregion

        #region FINANCIAL ENTRY PROCESSING INVOICE
        public string ExportFinancialEntrySales(List<FinEntry> ListData)
        {
            string filename = ConfigurationSettings.AppSettings["ShareFolderXML"] + @"\FINENTRYSales" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xml";
            XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
            XElement elementRoot = new XElement("eExact", new XAttribute(XNamespace.Xmlns + "xsi", ns),
                new XAttribute(ns + "noNamespaceSchemaLocation", "eExact-Schema.xsd"));


            doc.Add(elementRoot);
            XElement elementGLEntries = new XElement("GLEntries");

            foreach (FinEntry item in ListData)
            {
                var queryST = from ST in DS.ISHCMC_V_StudentListWithDebtors
                              where ST.StudentID == item.StudentID
                              select ST;
                var queryHumres = from Humres in DS.humres
                                  where Humres.usr_id == Environment.UserName
                                  select Humres;
                if (queryST.Count() > 0 && queryHumres.Count() > 0)
                {
                    ISHCMC_V_StudentListWithDebtor student = queryST.First();
                    string resourcecode = queryHumres.First().res_id.ToString();


                    XElement elementGLEntry = new XElement("GLEntry");

                    XElement elementGLEntryDesc = new XElement("Description", "Student " + item.StudentID + " Invoice No " + item.InvoiceNo);
                    elementGLEntry.Add(elementGLEntryDesc);

                    XElement elementGLEntryDate = new XElement("Date", item.ReceiptDate.ToString("dd/MM/yyyy"));
                    elementGLEntry.Add(elementGLEntryDate);

                    XElement elementGLEntryJnr = new XElement("Journal", new XAttribute("code", item.JournalNumber.ToString()));
                    XElement elementGLEntryGLAccount = new XElement("GLAccount", new XAttribute("code", item.GLAccount));
                    XElement elementGLEntryGLPaymentInTransit = new XElement("GLPaymentInTransit", new XAttribute("code", item.GLAccountOffset));
                    elementGLEntryJnr.Add(elementGLEntryGLAccount);
                    elementGLEntryJnr.Add(elementGLEntryGLPaymentInTransit);
                    elementGLEntry.Add(elementGLEntryJnr);

                    XElement elementGLEntryCC = new XElement("Costcenter", new XAttribute("code", student.School));
                    elementGLEntry.Add(elementGLEntryCC);

                    XElement elementGLEntryResource = new XElement("Resource", new XAttribute("code", student.School));
                    elementGLEntry.Add(elementGLEntryResource);

                    XElement elementGLEntryAmount = new XElement("Amount");
                    XElement elementGLEntryCurrency = new XElement("Currency", new XAttribute("code", item.Currency));
                    elementGLEntryAmount.Add(elementGLEntryCurrency);
                    elementGLEntry.Add(elementGLEntryAmount);

                    elementGLEntry.Add(this.GetElementFINLineCashBank(item, student, resourcecode, "Credit", item.GLAccountOffset));


                    elementGLEntries.Add(elementGLEntry);



                }
            }


            elementRoot.Add(elementGLEntries);
            doc.Save(filename);
            return filename;
        }
        private XElement GetElementFINLineSales(FinEntry item, ISHCMC_V_StudentListWithDebtor student, string resourcecode, string type, string glaccount)
        {
            XElement elementGLEntryLine = new XElement("FinEntryLine"
                      , new XAttribute("number", "1")
                      , new XAttribute("type", "N")
                      , new XAttribute("subtype", "K"));


            XElement elementGLEntryLDate = new XElement("Date", item.ReceiptDate.ToString("dd/MM/yyyy"));
            elementGLEntryLine.Add(elementGLEntryLDate);
            XElement elementGLEntryLGLAccount = new XElement("GLAccount", new XAttribute("code", glaccount));
            elementGLEntryLine.Add(elementGLEntryLGLAccount);

            XElement elementGLEntryLDesc = new XElement("Description", "Student " + item.StudentID + " Invoice No " + item.InvoiceNo);
            elementGLEntryLine.Add(elementGLEntryLDesc);

            XElement elementGLEntryLCC = new XElement("Costcenter", new XAttribute("code", student.School));
            elementGLEntryLine.Add(elementGLEntryLCC);

            XElement elementGLEntryLCU = new XElement("Costunit", new XAttribute("code", student.Grade));
            elementGLEntryLine.Add(elementGLEntryLCU);
            if (item.DebtorCode != null)
            {
                if (item.DebtorCode.Length > 3)
                {

                    XElement elementGLEntryLAccount = new XElement("Debtor", new XAttribute("code", item.DebtorCode.Trim()),
                        new XAttribute("number", item.DebtorCode.Trim()));
                    elementGLEntryLine.Add(elementGLEntryLAccount);

                }
            }
            else
            {

                XElement elementGLEntryLAccount = new XElement("Debtor", new XAttribute("code", student.debnr),
                    new XAttribute("number", student.debnr));
                elementGLEntryLine.Add(elementGLEntryLAccount);

            }
            XElement elementGLEntryLResource = new XElement("Resource", new XAttribute("code", resourcecode));
            elementGLEntryLine.Add(elementGLEntryLResource);

            XElement elementGLEntryLQuantity = new XElement("Quantity", "1");
            elementGLEntryLine.Add(elementGLEntryLQuantity);


            XElement elementGLEntryLAmount = new XElement("Amount");
            if (type == "Debit")
            {
                XElement elementGLEntryLAmountDebit = new XElement("Debit", item.Amount);
                elementGLEntryLAmount.Add(elementGLEntryLAmountDebit);

                XElement elementGLEntryLAmountCredit = new XElement("Credit", "0");
                elementGLEntryLAmount.Add(elementGLEntryLAmountCredit);
            }
            else
            {
                XElement elementGLEntryLAmountDebit = new XElement("Debit", "0");
                elementGLEntryLAmount.Add(elementGLEntryLAmountDebit);

                XElement elementGLEntryLAmountCredit = new XElement("Credit", item.Amount);
                elementGLEntryLAmount.Add(elementGLEntryLAmountCredit);
            }

            elementGLEntryLine.Add(elementGLEntryLAmount);
            XElement elementGLEntryFinReference = new XElement("FinReferences");

            XElement elementGLEntryYourRef = new XElement("YourRef", item.Ref);
            elementGLEntryFinReference.Add(elementGLEntryYourRef);
            elementGLEntryLine.Add(elementGLEntryFinReference);


            return elementGLEntryLine;
        }
        #endregion

    }
}
